import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select, Popconfirm, Tabs, message } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { enum2options } from '@/utils/enum2options';
import { Access } from '@umijs/max'
import TableContainer from '@/components/TableContainer';
import RecordDrawer from './components/RecordDrawer';
import { queryPointsGoodsList, savePointsGoodsBatch, delPointsGoodsBatch } from "@/services/goods"
import { PointsGoodsState, PointsGoodsType } from '@/constants/enums/goods';
import { jump2target } from '@/utils/common';
import TableActions from '@/components/TableActions';

const GoodsPage: React.FC = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<Goods.QueryPointsGoodsListParams>({
    pageNum: 1, pageSize: 10, type: PointsGoodsType.充电优惠券,
  })
  const list = useRequest(() => queryPointsGoodsList(searchParams), {
    refreshDeps: [searchParams],
  })
  const saveReq = useRequest(savePointsGoodsBatch, {manual: true})
  const delReq = useRequest(delPointsGoodsBatch, {manual: true})
  const [checkedId, setCheckedId] = useState<string>()
  const [tabKey, setTabKey] = useState(PointsGoodsType.充电优惠券)

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      state: formValues.state,
      pageNum: 1,
    })
  }
  const onTabKeyChange = (key: PointsGoodsType) => {
    setTabKey(key)
    setSearchParams({
      ...searchParams,
      type: key,
      pageNum: 1,
    })
  }
  const offGoods = async (record: Goods.PointsGoods) => {
    return saveReq
    .runAsync({reqList: [{integralId: record.integralId, state: PointsGoodsState.下架}]})
    .then(() => {
      message.success('下架成功')
      list.refresh()
    })
  }
  const onGoods = async (record: Goods.PointsGoods) => {
    return saveReq
    .runAsync({reqList: [{integralId: record.integralId, state: PointsGoodsState.上架}]})
    .then(() => {
      message.success('上架成功')
      list.refresh()
    })
  }
  const _delGoods = async (record: Goods.PointsGoods) => {
    return delReq
    .runAsync({ids: [record.integralId]})
    .then(() => {
      message.success('删除成功')
      list.refresh()
    })
  }

  const openEditPage = (record?: Goods.PointsGoods) => {
    jump2target('/mall/points/goods/edit', {
      name: record ? '编辑积分商品' : '添加积分商品',
      params: record,
      needRefresh: true,
    })
  }

  const columns: ColumnsType<Goods.PointsGoods> = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 220,
      render: (_, record) => {
        return <div className={`w-80 flex`}>
        <img className="w-14 h-14 mr-2 shrink-0" src={record.img?.split(',')[0]} />
        <div className="grow">
          <div>{record.goodsName}</div>
        </div>
      </div>
      }
    },
    {
      title: '分组',
      width: 120,
      dataIndex: 'categoryName'
    },
    {
      title: '价格',
      width: 160,
      key: 'price',
      render: (_, record) => {
        return <div className='flex flex-col'>
          <div>积分：{record.integralPrice}</div>
          <div>人民币：{record.goodsPrice || 0}</div>
        </div>
      }
    },
    {
      title: '限兑数量',
      width: 120,
      dataIndex: 'purchaseNum',
      render: val => val || '不限量',
    },
    {
      title: '库存',
      width: 120,
      dataIndex: 'num',
      render: val => val || '不限量',
    },
    {
      title: '创建时间',
      width: 160,
      dataIndex: 'createTime',
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '商品状态',
      width: 120,
      dataIndex: 'state',
      render: val => {
        switch (val) {
          case PointsGoodsState.上架: return '上架'
          case PointsGoodsState.下架: return '下架'
          default: return '--'
        }
      }
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        return (
          <TableActions>
            <a key='edit' onClick={() => openEditPage(record)}>编辑</a>
            <Access accessible={record.state === PointsGoodsState.上架}>
              <Popconfirm title='确认下架该商品吗？' onConfirm={async () => offGoods(record)}>
                <a>下架</a>
              </Popconfirm>
            </Access>
            <Access accessible={record.state === PointsGoodsState.下架}>
              <Popconfirm title='确认上架该商品吗？' onConfirm={async () => onGoods(record)}>
                <a>上架</a>
              </Popconfirm>
            </Access>
            <Access accessible={record.state === PointsGoodsState.下架}>
              <Popconfirm title='确认删除该商品吗？' onConfirm={async () => _delGoods(record)}>
                <a>删除</a>
              </Popconfirm>
            </Access>
          </TableActions>
        )
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshPointsGoodsList', refresh)
    return () => {
      window.removeEventListener('refreshPointsGoodsList', refresh)
    }
  }, [])

  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={() => openEditPage()}>新建活动</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form name='searchPointGoodsForm' colon={false} form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='状态' name='state'>
                <Select placeholder='请选择' variant='borderless' options={enum2options(PointsGoodsState)} style={{width: '100%'}} allowClear />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Tabs
        items={[
          {label: '充电优惠券', key: PointsGoodsType.充电优惠券},
          {label: '商品优惠券', key: PointsGoodsType.优惠券},
          {label: '商品', key: PointsGoodsType.商品},
        ]}
        activeKey={tabKey}
        onChange={val => onTabKeyChange(val as PointsGoodsType)}
        tabBarExtraContent={{
          left: <div style={{padding: 8}}></div>
        }}
      />
      <Table<Goods.PointsGoods>
        rowKey='goodsId'
        loading={list.loading}
        dataSource={list.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: list.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
      <RecordDrawer
        id={checkedId}
        onCancel={() => setCheckedId(undefined)}
      />
    </TableContainer>
  );
};

export default GoodsPage;
